/* eslint-disable no-param-reassign */
import { round } from 'lodash';
import { SETTLEMENT_TYPE } from '@/config/constants';

/**
 * 是否是标品
 * @param type
 * @returns {boolean}
 */
export const isStander = (type: string) => SETTLEMENT_TYPE.key.STANDER === type;

/**
 * @method 计算预估收益
 * @param basePrice 基础价格
 * @param rate
 * @returns {string}
 */
export const calcBenefit = (basePrice = 0, rate = 0) => {
  rate = rate || 0;
  return basePrice && basePrice !== 0 ? round(basePrice * (1 - rate / 100), 2) : '';
};

/**
 * 根据预估收益反算基础价格
 */
export const calcBasePrice = (beneFit: any = 0, rate = 0) => {
  rate = rate || 0;
  return beneFit !== '' && beneFit !== 0 ? round(beneFit / (1 - rate / 100), 2) : '';
};

export function isNotEmpty(str: any) {
  return str !== null && str !== undefined;
}

/**
 * 拼接地址
 * @param province
 * @param city
 * @param county
 * @param address
 * @param separator
 * @returns {string}
 */
export const handleFullAddress = (province = '', city = '', county = '', address = '', separator = ' ') => {
  const paddingSpace = (str: string) => (str ? `${str}${separator}` : str || '');
  return `${paddingSpace(province)}${paddingSpace(city)}${paddingSpace(county)}${address || ''}`;
};

// 价格驼峰
export function splitPrice(price: number | string | undefined = 0) {
  const dealPrice = isNotEmpty(price) ? round(Number(price), 2).toFixed(2) : '';
  const [firstArr, lastArr] = dealPrice.split('.');
  return [firstArr, lastArr];
}

export function debounce(method: any, wait: number): any {
  let timeout: any;
  let result;
  const debounced = function (...args: any) {
    return new Promise((resolve) => {
      // @ts-ignore
      const context = this;
      if (timeout) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(() => {
        result = method.apply(context, args);
        // 将原函数的返回值传给resolve
        resolve(result);
      }, wait);
    });
  };

  return debounced;
}
